// /src/http/request.js
// 🔴 一定要在最上面先打补丁
import {
	setupMock
} from '@/mock'

// 不依赖 import.meta，简单粗暴：开发期启用，发布关掉
const ENABLE_MOCK = true // 开发就填 true；发版改成 false 即可
try {
	setupMock({
		enable: ENABLE_MOCK,
		delay: 250
	})
	console.log('[HTTP BOOT] mockPatched =', !!uni.request.__isMockPatched)
} catch (e) {
	console.warn('[HTTP BOOT] setupMock failed:', e)
}

// 下面才是你原有的封装……
const BASE_URL = '' // 用相对地址 /api/...，让 mock 能命中；要拼网关就填你的网关

const joinURL = (b, p) =>
	String(b).replace(/\/+$/, '') + '/' + String(p || '').replace(/^\/+/, '')

const request = (options) => {
	const url = joinURL(BASE_URL, options.url)
	const token = uni.getStorageSync('token') || ''

	const defaultOptions = {
		url,
		method: options.method || 'GET',
		header: {
			'Content-Type': 'application/json',
			'skill-pact': token
		},
		data: options.data || {},
		timeout: 10000,
	}

	// 调试：每次请求都看一下是否已补丁
	console.log(`[HTTP] ${defaultOptions.method} ${defaultOptions.url} mockPatched=`, !!uni.request.__isMockPatched)

	uni.showLoading({
		title: '加载中...',
		mask: true
	})

	return new Promise((resolve, reject) => {
		uni.request({
			...defaultOptions,
			success: (res) => {
				if (res.statusCode === 200) return resolve(res.data)
				if (res.statusCode === 401) {
					uni.removeStorageSync('token')
					uni.removeStorageSync('userInfo')
					uni.showToast({
						title: '登录已过期，请重新登录',
						icon: 'none',
						duration: 2000
					})
					setTimeout(() => uni.reLaunch({
						url: '/pages/login/login'
					}), 2000)
					return reject(res)
				}
				uni.showToast({
					title: res.data?.message || '请求失败',
					icon: 'none'
				})
				reject(res)
			},
			fail: (err) => {
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				})
				reject(err)
			},
			complete: () => uni.hideLoading()
		})
	})
}

const http = {
	get(url, data) {
		return request({
			url,
			method: 'GET',
			data
		})
	},
	post(url, data) {
		return request({
			url,
			method: 'POST',
			data
		})
	},
	put(url, data) {
		return request({
			url,
			method: 'PUT',
			data
		})
	},
	delete(url, data) {
		return request({
			url,
			method: 'DELETE',
			data
		})
	},
}

export default http